import { IValidationService } from './interfaces/IValidationService';
import { ICacheService } from './interfaces/ICacheService';
import { ValidationResult, LLMProvider } from '../types/index';
import { ModelService } from './ModelService';

export class ValidationService implements IValidationService {
  private modelService: ModelService;
  private cacheService: ICacheService;
  private readonly VALIDATION_CACHE_EXPIRY_MS = 30 * 60 * 1000; // 30分钟

  constructor(modelService: ModelService, cacheService: ICacheService) {
    this.modelService = modelService;
    this.cacheService = cacheService;
  }

  async validateApiKey(
    provider: LLMProvider,
    apiKey: string,
    baseURL?: string
  ): Promise<ValidationResult> {
    // 基础验证
    if (!apiKey || !apiKey.trim()) {
      return {
        isValid: false,
        error: {
          code: 'INVALID_API_KEY',
          message: 'API Key 不能为空',
          suggestion: '请输入有效的 API Key'
        }
      };
    }

    // 检查缓存
    const cacheKey = this.getValidationCacheKey(provider, apiKey);
    const cached = await this.cacheService.get<ValidationResult>(cacheKey);
    if (cached && cached.isValid) {
      return cached;
    }

    // 获取适配器并验证
    const adapter = this.modelService.getAdapter(provider);
    if (!adapter) {
      return {
        isValid: false,
        error: {
          code: 'UNSUPPORTED_PROVIDER',
          message: `不支持的LLM供应商: ${provider}`,
          suggestion: '请选择支持的供应商'
        }
      };
    }

    try {
      const result = await adapter.validateApiKey(apiKey, baseURL);
      
      // 只有验证成功时才缓存结果
      if (result.isValid) {
        await this.cacheService.set(cacheKey, result, this.VALIDATION_CACHE_EXPIRY_MS);
      }
      
      return result;
    } catch (error) {
      console.error('API Key 验证失败:', error);
      return {
        isValid: false,
        error: {
          code: 'VALIDATION_ERROR',
          message: '验证过程中发生错误',
          suggestion: '请检查网络连接并重试'
        }
      };
    }
  }

  async validateConfig(
    provider: LLMProvider,
    apiKey: string,
    modelName: string,
    baseURL: string
  ): Promise<ValidationResult> {
    // 首先验证 API Key
    const apiKeyResult = await this.validateApiKey(provider, apiKey, baseURL);
    if (!apiKeyResult.isValid) {
      return apiKeyResult;
    }

    // 验证模型名称
    try {
      const models = await this.modelService.getModels(provider);
      const modelExists = models.some(model => model.id === modelName);
      
      if (!modelExists && models.length > 0) {
        return {
          isValid: false,
          error: {
            code: 'INVALID_MODEL',
            message: `模型 "${modelName}" 不存在或不可用`,
            suggestion: `请选择可用的模型，或检查模型名称是否正确`
          }
        };
      }

      // 如果所有验证都通过
      return {
        isValid: true,
        metadata: {
          ...apiKeyResult.metadata,
          modelName,
          availableModels: models.map(m => m.id)
        }
      };
    } catch (error) {
      // 如果获取模型列表失败，但API Key有效，仍然认为配置可能有效
      console.warn('无法验证模型名称:', error);
      return {
        isValid: true,
        metadata: {
          ...apiKeyResult.metadata,
          modelName,
          warning: '无法验证模型名称，但API Key有效'
        }
      };
    }
  }

  async getCachedValidation(
    provider: LLMProvider,
    apiKey: string
  ): Promise<ValidationResult | null> {
    const cacheKey = this.getValidationCacheKey(provider, apiKey);
    return await this.cacheService.get<ValidationResult>(cacheKey);
  }

  /**
   * 清除指定API Key的验证缓存
   */
  async clearValidationCache(provider: LLMProvider, apiKey: string): Promise<void> {
    const cacheKey = this.getValidationCacheKey(provider, apiKey);
    await this.cacheService.delete(cacheKey);
  }

  /**
   * 清除所有验证缓存
   */
  async clearAllValidationCache(): Promise<void> {
    // 这里需要实现清除所有验证相关的缓存
    // 具体实现依赖于缓存服务的能力
    const providers: LLMProvider[] = ['openai', 'anthropic', 'openrouter', 'openai-compatible'];
    
    // 由于无法直接遍历所有可能的API Key，这里只是示例
    // 在实际应用中，可能需要维护一个已验证API Key的列表
    try {
      await this.cacheService.clearExpired();
    } catch (error) {
      console.warn('清除过期缓存失败:', error);
    }
  }

  /**
   * 批量验证多个配置
   */
  async validateMultipleConfigs(
    configs: Array<{
      provider: LLMProvider;
      apiKey: string;
      modelName: string;
      baseURL: string;
    }>
  ): Promise<ValidationResult[]> {
    // 使用Promise.all替代Promise.allSettled以兼容旧版本
    const results = await Promise.all(
      configs.map(async config => {
        try {
          return await this.validateConfig(config.provider, config.apiKey, config.modelName, config.baseURL);
        } catch (error) {
          return {
            isValid: false,
            error: {
              code: 'VALIDATION_ERROR',
              message: '验证过程中发生错误',
              suggestion: '请检查配置并重试'
            }
          } as ValidationResult;
        }
      })
    );

    return results;
  }

  private getValidationCacheKey(provider: LLMProvider, apiKey: string): string {
    // 为了安全，不直接使用完整的API Key作为缓存键
    // 使用API Key的哈希值（这里简化为前8位和后4位）
    const maskedKey = apiKey.length > 12 
      ? `${apiKey.substring(0, 8)}...${apiKey.substring(apiKey.length - 4)}`
      : apiKey;
    
    return `validation_${provider}_${maskedKey}`;
  }
}